package cn.jiemusic.utils;

import cn.jiemusic.domain.po.Music;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.min;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.datatype.Artwork;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;


@Slf4j
@Component
public class AudioUtils {
    @Value("${project-config.base-path}")
    private String basePath;

    // 提取音乐信息（包括时长、元数据和封面图）
    public Music extractMusicInfo(MultipartFile multipartFile, Long mid) throws IOException {
        File tempFile = File.createTempFile("temp-audio", ".mp3");
        multipartFile.transferTo(tempFile);

        Music music = new Music();
        try {
            // 读取 MP3 文件
            AudioFile audioFile = AudioFileIO.read(tempFile);

            // 获取音频的标签
            Tag tag = audioFile.getTag();

            // 提取元数据，确保不会返回 null
            music.setArtist(tag.getFirst(FieldKey.ARTIST) != null ? tag.getFirst(FieldKey.ARTIST) : "未知艺术家");
            music.setAlbum(tag.getFirst(FieldKey.ALBUM) != null ? tag.getFirst(FieldKey.ALBUM) : "未知专辑");
            music.setName(tag.getFirst(FieldKey.TITLE) != null ? tag.getFirst(FieldKey.TITLE) : "未知歌曲");

            // 获取音频时长
            long durationMillis = audioFile.getAudioHeader().getTrackLength() * 1000L; // 转换为毫秒
            long minutes = durationMillis / 60000;
            long seconds = (durationMillis % 60000) / 1000;
            music.setDuration(String.format("%02d:%02d", minutes, seconds));

            // 提取封面图
            Artwork artwork = tag.getFirstArtwork();
            if (artwork != null) {
                byte[] coverData = artwork.getBinaryData();
                TransferUtils.uploadCover(coverData, basePath, mid);
            } else {
                log.info("该音频文件没有封面图");
            }

            return music;
        } catch (IOException e) {
            log.error("读取音频信息失败，错误: {}", e.getMessage());
        } catch (Exception e) {
            log.error("处理音频文件时出错，错误: {}", e.getMessage());
        } finally {
            tempFile.deleteOnExit();
        }
        return null; // 如果发生异常，返回 null
    }

}
